package com.xiaoshuidi.cloud.framework.fadada.core.service;

import com.fadada.sdk.utils.crypt.FddEncryptTool;
import com.fadada.sdk.utils.crypt.MsgDigestUtil;
import com.xiaoshuidi.cloud.framework.common.util.http.OkHttpClientUtil;
import com.xiaoshuidi.cloud.framework.fadada.core.FadadaContractServiceApi;
import com.xiaoshuidi.cloud.framework.fadada.core.enums.FadadaReturnCodeConstants;
import com.xiaoshuidi.cloud.framework.fadada.core.service.dto.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fadada.sdk.base.client.FddBaseClient;
import com.fadada.sdk.base.model.req.*;
import com.fadada.sdk.verify.client.FddVerifyClient;
import com.fadada.sdk.verify.model.req.CancelExtsignAutoPageParams;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description:
 * @author: zhaoyu
 * @date: 2023/4/24
 */
@Slf4j
@Service
@Data
public class FadadaContractServiceApiImpl implements FadadaContractServiceApi {
    @Value("${fadada.app_id}")
    private String APPID;
    @Value("${fadada.app_secret}")
    private String APPKEY;
    @Value("${fadada.version}")
    private String V;
    @Value("${fadada.host}")
    private String HOST;

    @Override
    public AddSignatureRes addSignature(AddSignatureParams params) {
        FddBaseClient baseClient = new FddBaseClient(APPID, APPKEY, V, HOST);
//        AddSignatureParams params = new AddSignatureParams();
//        params.setCustomerId("此处填入实名认证通过后的客户编号"); //客户编号
//        //下面章图片base64、签章图片、图片公网地址三选一
//        params.setSignatureImgBase64(""); //签章图片base64
//        params.setFile(new File("D:\\sign.png")); //签章图片
//        params.setImgUrl(""); //签章图片公网地址
        String result = baseClient.invokeAddSignature(params);
        log.info("法大大印章上传返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse)){
                String data = fadadaResponse.getData();
                if (StringUtils.isNotBlank(data)){
                    AddSignatureRes addSignatureRes = JSONObject.parseObject(data, AddSignatureRes.class);
                    return addSignatureRes;
                }
            }
        }
        return null;
    }

    @Override
    public CustomSignatureRes customSignature(CustomSignatureParams params) {
        FddBaseClient baseClient = new FddBaseClient(APPID, APPKEY, V, HOST);
//        CustomSignatureParams params = new CustomSignatureParams();
//        params.setContent("XX测试责任有限公司"); //印章展示的文字
//        params.setCustomerId("此处填写实名认证通过的客户编号"); //客户编号
        String result = baseClient.invokeCustomSignature(params);
        log.info("法大大自定义印章返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse)){
                String data = fadadaResponse.getData();
                if (StringUtils.isNotBlank(data)){
                    CustomSignatureRes customSignatureRes = JSONObject.parseObject(data, CustomSignatureRes.class);
                    return customSignatureRes;
                }
            }
        }
        return null;
    }

    @Override
    public Boolean uploaddocs(UploadDocsParams params) {
        FddBaseClient baseClient = new FddBaseClient(APPID, APPKEY, V, HOST);
//        UploadDocsParams params = new UploadDocsParams();
//        params.setContractId("UUID1231254135136"); //自定义合同id
//        params.setDocTitle("授权代理协议范本"); //合同标题
//        //PDF文档和下载地址二选一
//        params.setFile(new File("D:\\授权协议.pdf")); //PDF文档
//        params.setDocUrl(""); //合同公网下载地址
//        params.setDocType(".pdf"); //合同类型 目前仅支持pdf格式
        String result = baseClient.invokeUploadDocs(params);
        log.info("法大大合同上传返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse) && Integer.valueOf(fadadaResponse.getCode()).intValue() == FadadaReturnCodeConstants.OPERATION_SUCCESS.getCode().intValue()){
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean uploadtemplate(UploadTemplateParams params) {
        FddBaseClient baseClient = new FddBaseClient(APPID, APPKEY, V, HOST);
//        UploadTemplateParams params = new UploadTemplateParams();
//        params.setTemplateId("UUID1231241254121");  // 平台自定义唯一模板编号
//        //下列PDF模板和文档地址二选一
//        params.setFile(new File("D:\\入职协议模板.pdf")); // PDF模板
//        params.setDocUrl(""); // 文档地址
        String result = baseClient.invokeUploadTemplate(params);
        log.info("法大大模板上传返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse) && Integer.valueOf(fadadaResponse.getCode()).intValue() == FadadaReturnCodeConstants.SUCCESS.getCode().intValue()){
                return true;
            }
        }
        return false;
    }

    @Override
    public FadadaUploadResponse generateContract(GenerateContractParams params) {
        FddBaseClient baseClient = new FddBaseClient(APPID, APPKEY, V, HOST);
//        GenerateContractParams params = new GenerateContractParams();
//        params.setTemplateId(TEMPLATEID);  //模板编号
//        params.setContractId("UUID12312412541515"); //合同编号
//        //以下是非必填参数
//        params.setDocTitle(""); // 文档标题
//        params.setFontSize(""); //字体大小
//        params.setFontType(""); //字体类型
//        params.setParameterMap(getparamter()); //填充内容,json字符串
//        params.setDynamicTables(getdynamic_tables()); //动态表格
        // 在版本号设置为 2.1 时，实现了对填充内容和动态表单进行3DES加密
        baseClient.setVersion("2.1");
        String result = baseClient.invokeGenerateContract(params);
        log.info("法大大模板填充返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaUploadResponse fadadaResponse = JSONObject.parseObject(result, FadadaUploadResponse.class);
            if (Objects.nonNull(fadadaResponse)){
                return fadadaResponse;
            }
        }
        return null;
    }

    // 构造填充内容ParameterMap示例
    private String getparamter() {
        JSONObject paramter = new JSONObject();
        paramter.put("borrower","深圳法大大");
        return paramter.toString();
    }

    // 构造动态表格DynamicTables示例
    private String getdynamic_tables() {
        JSONArray dynamic_tables = new JSONArray();
        JSONObject dynamic2 = new JSONObject();
        dynamic2.put("insertWay", 0);//0新页面插入 1在某个关键字后面插入
        dynamic2.put("pageBegin", "1");//页码从1开始计算
        //dynamic2.put("keyword", "表格插入处");//insertWay=1时，传关键字
        dynamic2.put("cellHeight", "16.0");
        dynamic2.put("colWidthPercent", new int[] { 3, 4, 4, 4});
        dynamic2.put("theFirstHeader", "附二");
        dynamic2.put("cellHorizontalAlignment", "1");
        dynamic2.put("cellVerticalAlignment", "5");
        dynamic2.put("headers", new String[] { "序号", "借款人", "贷款人", "金额" });
        String row1[] = new String[] { "1", "小网", "小易",  "1000" };
        String row2[] = new String[] { "2", "小云", "小音",  "2000" };
        String row3[] = new String[] { "3", "小乐", "天马",  "3000" };
        dynamic2.put("datas", new String[][] { row1, row2, row3 });
        dynamic2.put("headersAlignment", "1");
        dynamic2.put("tableWidthPercentage", 80);
        dynamic_tables.add(dynamic2);
        System.out.println(dynamic_tables.toString());
        return dynamic_tables.toString();
    }

    @Override
    public String extsign(ExtSignParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        ExtSignParams params = new ExtSignParams();
//        params.setTransactionId("UUID12312414124");//平台自定义唯一交易号
//        params.setContractId("UUIDcontractid123123");//此处传入调用上传或填充合同接口成功时定义的合同编号
//        params.setCustomerId("UUIDcontractid123123");//此处传入认证成功后成功申请证书的客户编号
//        params.setDocTitle("如：租赁合同协议");
//        params.setPositionType("0");//0-关键字（默认）1-坐标
//        params.setSignKeyword("受托方签字");
//        params.setKeywordStrategy("0");//0-所有关键字签章 （默认） 1-第一个关键字签章 2-最后一个关键字签章
        String result = client.invokeExtSign(params);
        log.info("法大大手动签署返回数据：{}", result);
        return result;
    }

    @Override
    public String beforeAuthsign(BeforeAuthSignParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        BeforeAuthSignParams params = new BeforeAuthSignParams();
//        params.setTransactionId("");//平台自定义唯一交易号
//        params.setAuthType("1");//1:授权自动签（目前只能填1）
//        params.setContractId("");//指该份线上授权委托书的合同编号，自定义即可
//        params.setCustomerId("");//传入注册返回的个人或企业客户编号
//        params.setReturnUrl("");//同步通知签署结果地址
//        params.setNotifyUrl("");//异步通知签署结果地址
        String result = client.invokeBeforeAuthSign(params);
        log.info("法大大获取授权自动签页面接口返回数据：{}", result);
        return result;
    }

    @Override
    public String cancelExtsignAutoPage(CancelExtsignAutoPageParams params) {
        FddVerifyClient client = new FddVerifyClient(APPID, APPKEY, V, HOST);
//        CancelExtsignAutoPageParams params = new CancelExtsignAutoPageParams();
//        params.setCustomerId("");//已授权自动签的客户编号
//        params.setNotifyUrl("");//异步通知地址
//        params.setReturnUrl("");//同步跳转地址
        String result = client.invokeCancelExtsignAutoPage(params);
        log.info("法大大取消授权签协议接口返回数据：{}", result);
        return result;
    }

    @Override
    public GetAuthStatusRes getAuthStatus(GetAuthStatusParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        GetAuthStatusParams params = new GetAuthStatusParams();
//        params.setCustomerId("");//传入调用授权自动签接口授权之后的客户编号
        String result = client.invokeGetAuthStatus(params);
        log.info("法大大查询授权自动签状态接口返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse)){
                String data = fadadaResponse.getData();
                if (StringUtils.isNotBlank(data)){
                    GetAuthStatusRes getAuthStatusRes = JSONObject.parseObject(data, GetAuthStatusRes.class);
                    return getAuthStatusRes;
                }
            }
        }
        return null;
    }

    @Override
    public FadadaUploadResponse extsignAuto(ExtSignAutoParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        ExtSignAutoParams params = new ExtSignAutoParams();
//        params.setTransactionId("UUID12312414124");//平台自定义唯一交易号
//        params.setContractId("UUIDcontractid123123");//此处传入调用上传或填充合同接口成功时定义的合同编号
//        params.setCustomerId("UUIDcontractid123123");//此处传入认证成功后成功申请证书的客户编号
//        params.setDocTitle("如：租赁合同协议");
//        params.setPositionType("0");//0-关键字（默认）1-坐标
//        params.setSignKeyword("出租人签字");
//        params.setKeywordStrategy("0");//0：所有关键字签章  1：第一个关键字签章 ；   2：最后一个关键字签章
        String result = client.invokeExtSignAuto(params);
        log.info("法大大自动签署返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaUploadResponse fadadaResponse = JSONObject.parseObject(result, FadadaUploadResponse.class);
            if (Objects.nonNull(fadadaResponse)){
                return fadadaResponse;
            }
        }
        return null;
    }

    @Override
    public Boolean contractFiling(ContractFillingParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        ContractFillingParams params = new ContractFillingParams();
//        params.setContractId(""); //此处传入调用上传或填充合同接口成功时定义的合同编号
        String result = client.invokeContractFilling(params);
        log.info("法大大合同归档返回数据：{}", result);
        if (StringUtils.isNotBlank(result)){
            FadadaResponse fadadaResponse = JSONObject.parseObject(result, FadadaResponse.class);
            if (Objects.nonNull(fadadaResponse) && Integer.valueOf(fadadaResponse.getCode()).intValue() == FadadaReturnCodeConstants.OPERATION_SUCCESS.getCode().intValue()){
                return true;
            }
        }
        return false;
    }

    @Override
    public String downLoadContract(DownloadPdfParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        DownloadPdfParams params = new DownloadPdfParams();
//        params.setContractId(CONTRACTID); // 合同编号
//        //如下，传setPath参数可以直接保存文件到本地，不传则返回url
//        params.setPath(""); // 指定路径，如：D:\\pdf\\uuidNew.pdf
        String result = client.invokeDownloadPdf(params);
        log.info("法大大合同下载返回数据：{}", result);
        return result;
    }

    @Override
    public String viewContract(ViewPdfURLParams params) {
        FddBaseClient client = new FddBaseClient(APPID, APPKEY, V, HOST);
//        ViewPdfURLParams params = new ViewPdfURLParams();
//        params.setContractId("UUIDContractid1212415124"); //此处传入调用上传或填充合同接口成功时定义的合同编号
        String result = client.invokeViewPdfURL(params);
        log.info("法大大合同查看返回数据：{}", result);
        return result;
    }

    @Override
    public FadadaResponse companyInfoCompare(CompanyInfoCompareParams params) {
        try {
            String url = HOST + "company_info_compare.api";
            Map<String, String> content = new HashMap<>();
            content.put("company_name",params.getCompany_name());
            content.put("legal_name",params.getLegal_name());
            content.put("credit_no",params.getCredit_no());
//            content.put("licence_no","");
//            content.put("organization_no","");

            String timestamp = getTimestamp();
            String[] strings = MsgDigestUtil.sortforParameters(content);
            String sortVales = String.join("", strings);
            String sha1 = FddEncryptTool.sha1(APPID + FddEncryptTool.md5Digest(timestamp) + FddEncryptTool.sha1(APPKEY + sortVales));
            String msgDigest = new String(FddEncryptTool.Base64Encode(sha1.getBytes()));
            content.put("timestamp",timestamp);
            content.put("app_id",APPID);
            content.put("v",V);
            content.put("msg_digest",msgDigest);
            String responStr = OkHttpClientUtil.doPost(url, null, content);
            log.info("法大大企业信息匹配返回数据：{}", responStr);
            FadadaResponse fadadaResponse = JSONObject.parseObject(responStr, FadadaResponse.class);
            return fadadaResponse;
        } catch (Exception e) {
            log.error("company_info_compare接口异常，请求参数：{}，异常信息：{}",JSONObject.toJSONString(params), e);
            FadadaResponse fadadaResponse = new FadadaResponse();
            fadadaResponse.setCode("-1");
            fadadaResponse.setMsg(e.getMessage());
            return fadadaResponse;
        }
    }

    @Override
    public FadadaSyncCompanyRes syncCompanyAuto(SyncCompanyAutoParams params) {
        try {
            String url = HOST + "syncCompany_auto.api";

            String identy = params.getCompany_id() + "|" + params.getPhone();
            String encrypt = FddEncryptTool.encrypt(identy, APPKEY);

            Map<String, String> content = new HashMap<>();
            content.put("customer_name",params.getCustomer_name());
            content.put("email",params.getEmail());
            content.put("id_mobile",encrypt);
            String timestamp = getTimestamp();
            String sha1 = FddEncryptTool.sha1(APPID + FddEncryptTool.md5Digest(timestamp) + FddEncryptTool.sha1(APPKEY));
            String msgDigest = new String(FddEncryptTool.Base64Encode(sha1.getBytes()));
            content.put("timestamp", timestamp);
            content.put("app_id", APPID);
            content.put("v", V);
            content.put("msg_digest",msgDigest);
            String responStr = OkHttpClientUtil.doPost(url, null, content);
            log.info("法大大自动同步企业信息返回数据：{}", responStr);
            FadadaSyncCompanyRes response = JSONObject.parseObject(responStr, FadadaSyncCompanyRes.class);
            return response;
        } catch (Exception e) {
            log.error("syncCompany_auto接口异常，请求参数：{}，异常信息：{}",JSONObject.toJSONString(params), e);
            FadadaSyncCompanyRes fadadaResponse = new FadadaSyncCompanyRes();
            fadadaResponse.setCode("-1");
            fadadaResponse.setMsg(e.getMessage());
            return fadadaResponse;
        }
    }

    private String getTimestamp(){
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(ts);
    }
}
